import { defineStore } from 'pinia'
import { storage } from '@/utils'
import { getPermmenu, getPerson, loginApi, type LoginParams, type Person } from '@/api/login'
import type { MenuItem } from '@/api/menu'

export const useUserStore = defineStore('user', {
  state() {
    return {
      // 用户 TOKEN
      token: '',
      // 用户 信息
      info: null as Person | null,
      // 用户菜单
      menus: [] as MenuItem[]
    }
  },

  actions: {
    // 登录
    async login(params: LoginParams) {
      const result = await loginApi(params)

      this.token = result.token
      storage.set('token', result.token, result.expire)
      storage.set('refreshToken', result.refreshToken, result.refreshExpire)
    },

    // 退出
    logout() {},

    async get() {
      const info = await getPerson()
      const { menus } = await getPermmenu()
      this.info = info
      this.menus = menus
    }
  },

  persist: {
    paths: ['token']
  }
})
